from datetime import timedelta, datetime
from typing import Optional
from fastapi.security import OAuth2PasswordBearer
from fastapi.params import Depends
from sqlalchemy.engine import base
from jose import JWTError, jwt
from starlette import status
from database import SessionLocal
from sqlalchemy.orm import Session
from fastapi.exceptions import HTTPException
from api.v1.user import models, schemas

oauth2_schema = OAuth2PasswordBearer(tokenUrl="/user/login_user")
SECRET_KEY = "test123456" # 加密密钥
ALGORITHM = "HS256" #加密算法
ACCESS_TOKEN_EXPIRE_MINUTES = 30 #过期时间

# 生成token
def created_access_token(data: dict, expires_delta: Optional[timedelta] = None):
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + timedelta(minutes=15)
    to_encode.update({"exp": expire})
    encoded_jet = jwt.encode(claims=to_encode, key=SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jet

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

# 解析jwt
async def jwt_get_current_user(token: str =Depends(oauth2_schema), db: Session = Depends(get_db)):
    credentials_exception = HTTPException(
        status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"}
    )
    try:
        payload = jwt.decode(token=token, key=SECRET_KEY, algorithms=[ALGORITHM])
        username = payload.get("sub")
        if username is None:
            raise credentials_exception
    except JWTError:
        raise credentials_exception
    db_user = db.query(models.User).filter(models.User.username == username).first()
    if db_user is None:
        raise credentials_exception
    return db_user

# 通过token解析出用户信息
async def jwt_get_current_active_user(current_user: schemas.ReadUser = Depends(jwt_get_current_user)):
    if not current_user.state:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Inactive user")
    return current_user